﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using System.Configuration;
using MyMvc.IBLL;
using MyMvc.BLL;
using MyMvc.Common;
using MyMvc.Model.Models;

namespace GreenNew
{
    /// <summary>
    /// Meeting 的摘要说明
    /// </summary>
    public class BlueHomeHandler : IHttpHandler
    {
        string methodName = "";
        IArticleService _articleService = new ArticleService();
        INoteService _noteService = new NoteService();
        ICategoryTypeService _typeService = new CategoryTypeService();
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                methodName = context.Request.Params["method"];
                switch (methodName)
                {
                    case "GetArticlePaged":
                        int pageIndex = Convert.ToInt32(context.Request.Params["pageIndex"]);
                        int pageSize = Convert.ToInt32(context.Request.Params["pageSize"]);
                        int category = Convert.ToInt32(context.Request.Params["category"]);
                        string jsonString = JsonConvert.SerializeObject(GetArticlePaged(pageIndex, pageSize, category), Formatting.Indented, new JsonSerializerSettings
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                            ContractResolver = new ExcludePropertiesContractResolver(new List<string> { "AddFiles", "AboutArticles" })
                        });
                        context.Response.Write(jsonString);
                        break;
                    case "GetArticlePagedBySub":
                        pageIndex = Convert.ToInt32(context.Request.Params["pageIndex"]);
                        pageSize = Convert.ToInt32(context.Request.Params["pageSize"]);
                        category = Convert.ToInt32(context.Request.Params["category"]);
                        jsonString = JsonConvert.SerializeObject(GetArticlePagedBySub(pageIndex, pageSize, category), Formatting.Indented, new JsonSerializerSettings
                       {
                           ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                           ContractResolver = new ExcludePropertiesContractResolver(new List<string> { "AddFiles", "AboutArticles" })
                       });
                        context.Response.Write(jsonString);
                        break;
                    case "GetAllLatestArticle":
                        jsonString = JsonConvert.SerializeObject(GetAllLatestArticle(), Formatting.Indented, new JsonSerializerSettings
                       {
                           ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                           ContractResolver = new ExcludePropertiesContractResolver(new List<string> { "AddFiles", "AboutArticles" })
                       });

                        context.Response.Write(jsonString);
                        break;
                    case "Getcategorytype":
                        int Type = Convert.ToInt32(context.Request.Params["Type"]);
                        context.Response.Write(JsonConvert.SerializeObject(Getcategorytype(Type)));
                        break;
                    case "Savenote":
                        var jSetting = new JsonSerializerSettings();
                        jSetting.NullValueHandling = NullValueHandling.Ignore;
                        Note postData = JsonConvert.DeserializeObject<Note>(context.Request.Params["postData"], jSetting);
                        context.Response.Write(JsonConvert.SerializeObject(Savenote(postData)));
                        break;
                    case "Getpage":
                        int pageId = Convert.ToInt32(context.Request.Params["pageId"]);
                        context.Response.Write(JsonConvert.SerializeObject(Getpage(pageId)));
                        break;
                    //case "Getaboutarticle":
                    //    int articleId = Convert.ToInt32(context.Request.Params["articleId"]);
                    //    context.Response.Write(JsonConvert.SerializeObject(Getaboutarticle(articleId)));
                    //    break;
                }
            }
            catch (Exception ex)
            {
                JsonResponse response = new JsonResponse();
                response.success = false;
                response.ResponseData = ex.Message;
                context.Response.Write(JsonConvert.SerializeObject(response));
            }
        }
        public JsonResponse Getpage(int pageId)
        {
            JsonResponse jr = new JsonResponse();
            try
            {
                jr.ResponseData = _articleService.LoadEntities(a => a.ID == pageId, "AboutArticles").FirstOrDefault();
                jr.success = true;
            }
            catch (Exception ex)
            {
                jr.success = false;
            }
            return jr;
        }
        public JsonResponse Savenote(Note postData)
        {
            JsonResponse jr = new JsonResponse();
            try
            {
                _noteService.AddEntities(postData);
                jr.success = true;
            }
            catch (Exception ex)
            {
                jr.success = false;
            }
            return jr;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        public JsonResponse Getcategorytype(int type)
        {

            JsonResponse jr = new JsonResponse();
            try
            {
                jr.ResponseData = _typeService.LoadEntities(c => c.ParentId == type).ToList();
            }
            catch (Exception ex)
            {
                jr.success = false;
                jr.ResponseData = ex.Message;
            }
            return jr;
        }

        /// <summary>
        /// 获取一级类别数据（分页）
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public JsonResponse GetArticlePaged(int pageIndex, int pageSize, int category)
        {
            JsonResponse jr = new JsonResponse();
            try
            {
                jr.ResponseData = _articleService.LoadPagerEntities<DateTime>(pageSize, pageIndex, out jr.DataCount, (x) => x.Category == category, false, (x) => x.CreateDateTime).ToList();
                jr.PageCount = jr.DataCount % pageSize == 0 ? jr.DataCount / pageSize : jr.DataCount / pageSize + 1;
            }
            catch (Exception ex)
            {
                jr.success = false;
                jr.ResponseData = ex.Message;
            }
            return jr;
        }
        /// <summary>
        /// 获取二级类别数据（分页）
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public JsonResponse GetArticlePagedBySub(int pageIndex, int pageSize, int category)
        {
            JsonResponse jr = new JsonResponse();
            try
            {
                jr.ResponseData = _articleService.LoadPagerEntities<DateTime>(pageSize, pageIndex, out jr.DataCount, (x) => x.SubCategory == category, false, (x) => x.CreateDateTime).ToList();
                jr.PageCount = jr.DataCount % pageSize == 0 ? jr.DataCount / pageSize : jr.DataCount / pageSize + 1;
            }
            catch (Exception ex)
            {
                jr.success = false;
                jr.ResponseData = ex.Message;
            }
            return jr;
        }
        //public JsonResponse Getaboutarticle(int articleId)
        //{
        //    JsonResponse jr = new JsonResponse();
        //    try
        //    {
        //        //List<Article> sss = _articleService.LoadEntities(x => true, "AboutArticles").ToList();
        //        List<Article> list = _articleService.LoadEntities(x => x.ID == articleId, "AboutArticles").ToList();
        //        jr.ResponseData = _articleService.LoadEntities(x => x.ID == articleId, "AboutArticles").ToList();
        //    }
        //    catch (Exception ex)
        //    {
        //        jr.success = false;
        //        jr.ResponseData = ex.Message;
        //    }
        //    return jr;
        //}
        /// <summary>
        /// 获取所有类别最新的七条文章
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public JsonResponse GetAllLatestArticle()
        {
            JsonResponse jr = new JsonResponse();
            try
            {
                //List<Article> list = _articleService.LoadEntities(x => true, "AboutArticles").ToList();
                var source = _articleService.LoadEntities(a => 1 == 1).OrderByDescending(x => x.CreateDateTime);
                jr.ResponseData = source.GroupBy(s => s.Category).SelectMany(g => g.OrderByDescending(s => s.CreateDateTime).Take(7)).ToList();
                jr.success = true;
            }
            catch (Exception ex)
            {
                jr.success = false;
                jr.ResponseData = ex.Message;
            }
            return jr;
        }


        /// <summary>
        /// 获取当前类别最新的七条文章
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public JsonResponse GetLatestArticleByCategory(int category)
        {
            JsonResponse jr = new JsonResponse();
            try
            {
                jr.ResponseData = _articleService.LoadEntities(a => a.Category == category).OrderByDescending(x => x.CreateDateTime).Take(7).ToList();
                jr.success = true;
            }
            catch (Exception ex)
            {
                jr.success = false;
                jr.ResponseData = ex.Message;
            }
            return jr;
        }

        /// <summary>
        /// 根据类别获取所有文章
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public JsonResponse GetArticleByCategory(int category)
        {
            JsonResponse jr = new JsonResponse();
            try
            {
                jr.ResponseData = _articleService.LoadEntities(a => a.Category == category).ToList();
                jr.success = true;
            }
            catch (Exception ex)
            {
                jr.success = false;
                jr.ResponseData = ex.Message;
            }
            return jr;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class LatestArticle
    {
        /// <summary>
        /// 专业文献列表
        /// </summary>
        public List<Article> DocumentList { get; set; }
        /// <summary>
        /// 优势技术列表
        /// </summary>
        public List<Article> AdvantageList { get; set; }
        /// <summary>
        /// 工程案例列表
        /// </summary>
        public List<Article> CaseList { get; set; }

        /// <summary>
        /// 业务范围列表
        /// </summary>
        public List<Article> ExtentList { get; set; }
    }

}